package com.kldy8.kldyw.find.script;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.kldy8.kldyw.MyWebActivity;
import com.kldy8.kldyw.R;
import com.kldy8.kldyw.filmfactory.bean.Positions;
import com.kldy8.kldyw.find.script.bean.Levy;
import com.kldy8.kldyw.find.script.bean.ScripTypes;
import com.kldy8.kldyw.find.script.bean.Script;
import com.kldy8.kldyw.find.script.scriptshow.ScriptShowAdapter;
import com.kldy8.kldyw.find.script.scriptshow.ScriptSolicitationAdapter;
import com.kldy8.kldyw.logre.LoginActivity;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import com.kldy8.kldyw.system.UrlBuilder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;

/**
 * 剧本
 */
public class ScriptActivity extends AppCompatActivity
{
//    /** DrawerLayout */
//    private DrawerLayout mDrawerLayout;
//    /** 右边栏 */
//    private RelativeLayout right_drawer;
//    /** 右边栏打开/关闭状态 */
//    private final static int MSG_MODIFY_RIGHT_ONE = 1;
//    private final static int MSG_MODIFY_RIGHT_TWO = 2;


    private List<Positions> positionsList1 = new ArrayList<Positions>();
    private ScripTypes types1;
    private ScripTypes themes1;
    private ScripTypes ages1;


    private List<Positions> positionsList2 = new ArrayList<Positions>();
    private ScripTypes types2;
    private ScripTypes themes2;
    private ScripTypes ages2;

//    private List<Script> scriptList1 = new ArrayList<Script>();
//    private List<Levy> levyList2 = new ArrayList<Levy>();


    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private Toolbar toolbar;

    private int page1 = 1;
    private int page2 = 1;

    int  type_id1, theme_id1, age_id1;
    int  type_id2, theme_id2, age_id2;

    String order1,sort1;
    String order2,sort2,search;


    private LayoutInflater mInflater;
    private List<String> mTitleList = new ArrayList<>();//页卡标题集合
    private View view1, view2;

    ScriptShowAdapter adapter1;
    ScriptSolicitationAdapter adapter2;

    private XRefreshView  refreshView1,refreshView2;
    private List<View> mViewList = new ArrayList<>();//页卡视图集合
    private LinearLayout my_ly;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_script);

        //=========================侧边栏===================================
//        initRightView();

        /**
         * 自定义脚部文件
         */
        my_ly = (LinearLayout) findViewById(R.id.my_ly);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("剧本");//设置主标题
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true); // 决定左上角图标的右侧是否有向左的小箭头, true
        // 有小箭头，并且图标可以点击
        actionBar.setDisplayShowHomeEnabled(false);

        mViewPager = (ViewPager) findViewById(R.id.vp_view);
        mTabLayout = (TabLayout) findViewById(R.id.tabs);

        initViewPage();
        initData();

    }

//    //初始化侧边栏
//    private void initRightView()
//    {
//        //==========================侧边栏===============
//        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//        right_drawer = (RelativeLayout) findViewById(R.id.right_drawer);
//    }

//    private void initRightViewData(ScripTypes scripTypes)
//    {
//        LinearLayout relativeLayout = (LinearLayout) right_drawer.findViewById(R.id.right_main);
//        LayoutInflater inflater = getLayoutInflater();
//        View view = inflater.inflate(R.layout.script_view_group, null);
//        TextView textView = (TextView) view.findViewById(R.id.title_date);
//        FlowLayoutRadioGroup frg= (FlowLayoutRadioGroup) view.findViewById(R.id.flowLayout);
//        if (scripTypes != null)
//        {
//            textView.setText(scripTypes.title);
//            List<ScripTypes.Category> categoryList = scripTypes.categoryList;
//            for (ScripTypes.Category cate: categoryList)
//            {
//                RadioButton button  = new RadioButton(this);
//                button.setText(cate.name);
//                button.setTextColor(getResources().getColor(android.R.color.tertiary_text_dark));
//                frg.addView(button);
//            }
//        }
//        relativeLayout.addView(view);
//    }




    private void initData()
    {
        initShow(true,page1,"","",0,0,0);
        initLevyList(true,page2,"","",0,0,0,"");
    }

    /**
     *
     * @param page       页码（默认1）
     * @param order      排序：read人气/add_time时间
     * @param sort      排序方式：a升序/d降序
     * @param type_id   类型id
     * @param theme_id  主题id
     * @param age_id    年代id
     */
    private void initShow(final boolean isInit,final int page, String order, String sort, int type_id, int theme_id, int age_id)
    {
        ServerApi.script_list("" + page, order, sort, "" + type_id
                , "" + theme_id, "" + age_id, new ServerCallBack()
                {
                    @Override
                    public void onError(Request request, Exception e)
                    {
                        if (refreshView1!=null)
                        {
                            refreshView1.stopRefresh();
                            refreshView1.stopLoadMore();
                        }
//                        Toast.makeText(ScriptActivity.this,"系统错误",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onResponse(String response) throws JSONException
                    {
                        Log.e("......",response.toString());
                        JSONObject jsonObject = new JSONObject(response);
                        List<Script> scriptList1 = new ArrayList<Script>();
                        if ("0".equals(jsonObject.optString("code")))
                        {
                            page1++;
                            JSONObject objectData = jsonObject.optJSONObject("data");
                            JSONObject objectTypes = objectData.optJSONObject("types");
                            JSONObject objectThemes = objectData.optJSONObject("themes");
                            JSONObject objectAges = objectData.optJSONObject("ages");
                            JSONArray objectList = objectData.optJSONArray("list");


                            if (isInit == true)
                            {
                                page1 = 2;
                            }
                            if (null != objectTypes && objectTypes.length()>0)
                            {
                                    types1= new ScripTypes();
                                    types1.resolution(objectTypes);
                            }

                            if (null != objectThemes && objectThemes.length()>0)
                            {
                                    themes1= new ScripTypes();
                                    themes1.resolution(objectThemes);
                            }

                            if (null != objectAges && objectAges.length()>0)
                            {
                                    ages1 = new ScripTypes();
                                    ages1.resolution(objectAges);
                            }

                            if (null != objectList && objectList.length()>0)
                            {
                                for (int i = 0; i < objectList.length(); i++) {
                                    JSONObject object = objectList.optJSONObject(i);
                                    Script filmTalent = Script.resolution(object);
                                    if (filmTalent != null)
                                    {
                                        scriptList1.add(filmTalent);
                                    }
                                }
                            }

//                            //这里是更新侧边栏
//                            Message message = new Message();
//                            message.what = MSG_MODIFY_RIGHT_ONE;
//                            handler.sendMessage(message);

                            adapter1.replaceOrAdd(isInit,scriptList1);
                            adapter1.notifyDataSetChanged();
                        }
                        else  if ("14001".equals(jsonObject.optString("code")))
                        {
                            Toast.makeText(ScriptActivity.this, "暂无数据", Toast.LENGTH_LONG).show();
                        }
                        else  if ("10004".equals(jsonObject.optString("code")))
                        {
                            Intent intent2 = new Intent();
                            intent2.setClass(ScriptActivity.this, LoginActivity.class);
                            startActivity(intent2);
                            ScriptActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                        }

                        if (refreshView1!=null)
                        {
                            refreshView1.stopRefresh();
                            refreshView1.stopLoadMore();
                        }
                    }
                });
    }

    private void initLevyList(final boolean isInit,final int page, String order, String sort, int type_id, int theme_id, int age_id, String search)
    {
        ServerApi.levy_list("" + page, order, sort, "" + type_id
                , "" + theme_id, "" + age_id, search,new ServerCallBack()
        {
            @Override
            public void onError(Request request, Exception e)
            {
                if (refreshView2!=null)
                {
                    refreshView2.stopRefresh();
                    refreshView2.stopLoadMore();
                }
            }

            @Override
            public void onResponse(String response) throws JSONException
            {
                Log.e("TAG",response);
                JSONObject jsonObject = new JSONObject(response);
                List<Levy> levyList2 = new ArrayList<Levy>();
                if ("0".equals(jsonObject.optString("code")))
                {
                    page2++;
                    JSONObject objectData = jsonObject.optJSONObject("data");
                    JSONObject objectTypes = objectData.optJSONObject("types");
                    JSONObject objectThemes = objectData.optJSONObject("themes");
                    JSONObject objectAges = objectData.optJSONObject("ages");
                    JSONArray objectList = objectData.optJSONArray("list");

                    if (isInit == true)
                    {
                        page2 = 2;
                    }

                    if (null != objectTypes && objectTypes.length()>0)
                    {
                        types2= new ScripTypes();
                        types2.resolution(objectTypes);
                    }

                    if (null != objectThemes && objectThemes.length()>0)
                    {
                        themes2= new ScripTypes();
                        themes2.resolution(objectThemes);
                    }

                    if (null != objectAges && objectAges.length()>0)
                    {
                        ages2 = new ScripTypes();
                        ages2.resolution(objectAges);
                    }

                    if (null != objectList && objectList.length()>0)
                    {
                        for (int i = 0; i < objectList.length(); i++)
                        {
                            JSONObject object = objectList.optJSONObject(i);
                            Levy filmTalent = Levy.resolution(object);
                            if (filmTalent != null)
                            {
                                levyList2.add(filmTalent);
                            }
                        }
                    }

                    adapter2.replaceOrAdd(isInit,levyList2);
                    adapter2.notifyDataSetChanged();

                }
                else  if ("14001".equals(jsonObject.optString("code")))
                {
                    Toast.makeText(ScriptActivity.this, "暂无数据", Toast.LENGTH_LONG).show();
                }
                else  if ("10004".equals(jsonObject.optString("code")))
                {
                    Intent intent2 = new Intent();
                    intent2.setClass(ScriptActivity.this, LoginActivity.class);
                    startActivity(intent2);
                    ScriptActivity.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                }

                if (refreshView2!=null)
                {
                    refreshView2.stopRefresh();
                    refreshView2.stopLoadMore();
                }

            }
        });
    }

    private void initListView(View view)
    {
        ListView list_view = (ListView) view.findViewById(R.id.list_view);

        if (view == view1)
        {
            adapter1 = new ScriptShowAdapter(this, new ArrayList<Script>());
            list_view.setAdapter(adapter1);

            refreshView1 = (XRefreshView) view.findViewById(R.id.xrefreshview);
            refreshView1.setPullLoadEnable(true);

            //设置刷新完成以后，headerview固定的时间
            refreshView1.setPinnedTime(1000);
            refreshView1.setPullLoadEnable(true);
            refreshView1.setMoveForHorizontal(true);
            refreshView1.setAutoLoadMore(true);
            refreshView1.setEmptyView(R.layout.layout_emptyview);
            refreshView1.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refreshView1.startRefresh();
                }
            });

            refreshView1.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener()
            {

                @Override
                public void onRefresh()
                {
                    requestShowData();
                }

                @Override
                public void onLoadMore(boolean isSilence)
                {
                    moreShowData();
                }
            });
        }
        else
        {
            adapter2 = new ScriptSolicitationAdapter (this, new ArrayList<Levy>());
            list_view.setAdapter(adapter2);
            refreshView2 = (XRefreshView) view.findViewById(R.id.xrefreshview);
            refreshView2.setPullLoadEnable(true);

            //设置刷新完成以后，headerview固定的时间
            refreshView2.setPinnedTime(1000);
            refreshView2.setPullLoadEnable(true);
            refreshView2.setMoveForHorizontal(true);
            refreshView2.setAutoLoadMore(true);
            refreshView2.setEmptyView(R.layout.layout_emptyview);
            refreshView2.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refreshView2.startRefresh();
                }
            });

            refreshView2.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

                @Override
                public void onRefresh() {
                    requestLevyListData();
                }

                @Override
                public void onLoadMore(boolean isSilence) {
                    moreLevyListData();
                }
            });
        }
    }

    //刷新人才求职数据
    public void requestShowData()
    {
        initShow(true,1,"","",0,0,0);

    }
    //添加人才求职数据
    public void moreShowData()
    {
        initShow(false,page1,"","",0,0,0);

    }

    //刷新人才招募数据
    public void requestLevyListData()
    {
        initLevyList(true,1,"","",0,0,0,"");
    }
    //添加人才招募数据
    public void moreLevyListData()
    {
        initLevyList(false,page2,"","",0,0,0,"");
    }


    TextView tv1_1;
    TextView tv1_2;
    TextView tv1_3;

    TextView tv2_1;
    TextView tv2_2;
    TextView tv2_3;
    TextView tv2_4;
    TextView tv2_5;

    private void initViewPage()
    {
        mInflater = LayoutInflater.from(this);
        view1 = mInflater.inflate(R.layout.view_film_talent, null);
        initListView(view1);

        view2 = mInflater.inflate(R.layout.view_film_talent, null);
        initListView(view2);

        //添加页卡视图
        mViewList.add(view1);
        mViewList.add(view2);

        //添加页卡标题
        mTitleList.add("剧本展示");
        mTitleList.add("剧本征集");

        mTabLayout.setTabMode(TabLayout.MODE_FIXED);//设置tab模式，当前为系统默认模式
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(0)));//添加tab选项卡
        mTabLayout.addTab(mTabLayout.newTab().setText(mTitleList.get(1)));

        MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
        mViewPager.setAdapter(mAdapter);//给ViewPager设置适配器
        mTabLayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
        mTabLayout.setTabsFromPagerAdapter(mAdapter);//给Tabs设置适配器
    }
                        

    //ViewPager适配器
    class MyPagerAdapter extends PagerAdapter
    {
        private List<View> mViewList;

        public MyPagerAdapter(List<View> mViewList)
        {
            this.mViewList = mViewList;
        }

        @Override
        public int getCount()
        {
            return mViewList.size();//页卡数
        }

        @Override
        public boolean isViewFromObject(View view, Object object)
        {
            return view == object;//官方推荐写法
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position)
        {
            container.addView(mViewList.get(position));//添加页卡
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object)
        {
            container.removeView(mViewList.get(position));//删除页卡
        }

        @Override
        public CharSequence getPageTitle(int position)
        {
            return mTitleList.get(position);//页卡标题
        }

    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                finish();
                break;
//            case R.id.action_screen_sx_item:
////                mDrawerLayout.openDrawer(right_drawer);
//                break;

            case R.id.action_search:
                Intent intent = new Intent();
                intent.putExtra("url", UrlBuilder.URL_BASE_API+"/search/search_make_result?t_type=14&keyword=");
                intent.setClass(this, MyWebActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_notbtn, menu);
//        MenuItem menuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
//        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
//        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener()
//        {
//
//            public boolean onQueryTextSubmit(String query)
//            {
//                Log.e("tag",query);
//                Intent intent=new Intent(ScriptActivity.this,SearchActivity.class);  //方法1
//                Bundle bundle=new Bundle();
//                String[] languages=getResources().getStringArray(R.array.search_array);
//
//                bundle.putString(SearchActivity.TAG_ITEM,languages[0]);
//                bundle.putString(SearchActivity.TAG_KEY, query);
//                intent.putExtras(bundle);
//                startActivity(intent);
//                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
//
//                return true;
//            }
//
//            public boolean onQueryTextChange(String newText)
//            {
//                return true;
//            }
//        });



//        Log.d("Tag", "menu create");
//        MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
//            @Override
//            public boolean onMenuItemActionExpand(MenuItem item)
//            {
//                Toast.makeText(ScriptActivity.this, "onExpand", Toast.LENGTH_LONG).show();
//                return true;
//            }
//
//            @Override
//            public boolean onMenuItemActionCollapse(MenuItem item) {
//                Toast.makeText(ScriptActivity.this, "Collapse", Toast.LENGTH_LONG).show();
//                return true;
//            }
//        });
        return super.onCreateOptionsMenu(menu);
    }


    //===========================更新队列==============
    final Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            if(msg.what == 1)
            {
//                initRightViewData(types1);
//                initRightViewData(themes1);
//                initRightViewData(ages1);
            }
            else if(msg.what == 2)
            {
//                initRightViewData(types2);
//                initRightViewData(themes2);
//                initRightViewData(ages2);
            }
        }
    };

}
